﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Web.Mvc;
using System.Xml;
using System.Net;
using DNA.OpenAPI.Rss;
using DNA.OpenAPI.Atom;
using DNA.Mvc.UI;

namespace DNA.Mvc.Controllers
{
    //[HandlePartialError]
    public class AsyncWidgetController : AsyncController
    {
        [Widget("Feeds",
            Description = "Feeds is a widget that allows you subscript rss feed or atom feed.",
            ImageUrl = "images/rss.png",
            IconUrl = "images/rss_16.png")]
        [Property("Url", DisplayName = "Url", DefaultValue = "http://www.dotnetage.com/feeds/home/rss")]
        [Property("Layout", DisplayName = "Layout", DefaultValue = "TitleLayout")]
        [Property("Rows", DisplayName = "Display rows", ValueType = typeof(int), DefaultValue = 5)]
        [Property("TextLen", ValueType = typeof(int), DefaultValue = -1)]
        [Property("ShowFeedInfo", DisplayName = "Show feed info", ValueType = typeof(bool), DefaultValue = true)]
        [Property("ShowAuthor", ValueType = typeof(bool), DefaultValue = true)]
        [Property("ShowDate", ValueType = typeof(bool), DefaultValue = true)]
        public void FeedsAsync(string url, int rows) //,bool showAuthor,bool showDate,bool showFeedInfo,int textLen
        {
            if (!string.IsNullOrEmpty(url))
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers["Accept-Encoding"] = "gzip";
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
                request.AutomaticDecompression = DecompressionMethods.GZip;

                AsyncManager.OutstandingOperations.Increment();

                request.BeginGetResponse(new AsyncCallback(n =>
                {
                    var response = request.EndGetResponse(n);
                    var stream = response.GetResponseStream();
                    string xml = "";
                    using (var reader = new System.IO.StreamReader(stream))
                    {
                        xml = reader.ReadToEnd();
                    }
                    AsyncManager.Parameters["contentType"] = response.ContentType;
                    AsyncManager.Parameters["xml"] = xml;
                    AsyncManager.Parameters["rows"] = rows;
                    AsyncManager.OutstandingOperations.Decrement();
                }), rows);
            }
        }

        public ActionResult FeedsCompleted(string contentType, string xml, int rows)
        {
            ViewBag.HasError = false;
            if (!string.IsNullOrEmpty(xml))
            {
                var xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.LoadXml(xml);
                }
                catch (Exception e)
                {
                    ViewBag.HasError = true;
                    return PartialView("RssFeed", new RssChannel());
                }

                if (xmlDoc.DocumentElement.LocalName.Equals("feed", StringComparison.OrdinalIgnoreCase))
                {
                    var feed = DNA.Utility.XmlSerializerUtility.DeserializeFromXmlText(xml, typeof(AtomFeed));
                    return PartialView("AtomFeed", feed);
                }
                else
                {
                    var channel = DNA.Utility.XmlSerializerUtility.DeserializeFromXmlText(xmlDoc.DocumentElement.InnerXml, typeof(RssChannel));
                    return PartialView("RssFeed", channel);
                }
            }
            return PartialView("RssFeed");
        }
    }
}
